package lab4.nio;

import config.ATMData;
import config.Config;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;

/**
 * Created by Student on 17.12.2014.
 */
public class ClientDelayNIO {

    public static final int TESTS_NUMBER = 100;
    public static final int BUFFER_SIZE = 128;

    /**
     * Client send 2 commands to server.
     * First - 'get' - to get special object from server
     * Second - 'ok' - when client get this object
     * Server calculate time between the first command and the second
     *
     * @param args
     */
    public static void main(String[] args) {
        try (SocketChannel sc = SocketChannel.open()) {
            sc.connect(new InetSocketAddress(Config.ADDRESS, Config.PORT));

            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

            try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(Channels.newOutputStream(sc)))) {
                for (int i = 0; i < TESTS_NUMBER; i++) {
                    buffer.clear();

                    oos.writeObject("get");
                    oos.flush();

                    if (sc.read(buffer) > 0) {
                        try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array());
                             ObjectInputStream ois = new ObjectInputStream(bais);) {

                            System.out.println("Get: " + (ATMData) ois.readObject());
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                        oos.writeObject("ok");
                        oos.flush();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
